package com.brillilab.service.core.method.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.brillilab.dao.mapper.method.MethodPhaseMapper;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.enums.method.MethodSourceEnum;
import com.brillilab.domain.po.method.MethodPhase;
import com.brillilab.service.core.method.IMethodPhaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wuzhiyu
 * @Title: MethodPhaseServiceImpl
 * @ProjectName brill_lab
 * @Description: TODO
 * @date 2019/2/2210:12
 */
@Service
@Transactional
public class MethodPhaseServiceImpl implements IMethodPhaseService {
    @Resource
    private MethodPhaseMapper methodPhaseMapper;

    @Override
    public boolean savePhaseAndUpdateInitId(MethodPhase phase, Integer fromType) {
        methodPhaseMapper.insert(phase);
        LambdaQueryWrapper<MethodPhase> query = new LambdaQueryWrapper<>();
        query.eq(MethodPhase::getId, phase.getId());
        MethodPhase mp = new MethodPhase();
        mp.setId(phase.getId());
        if (MethodSourceEnum.CREATE.getSourceType().equals(fromType) || phase.getSourcePhaseId() == null) {
            mp.setSourcePhaseId(phase.getId());
        }
        mp.setInitPhaseId(phase.getId());
        methodPhaseMapper.update(mp, query);
        return true;
    }

    @Override
    public List<MethodPhase> listByMethodId(Long methodId, BoolEnum isDelete) {
        LambdaQueryWrapper<MethodPhase> query = new LambdaQueryWrapper<>();
        query.eq(MethodPhase::getMethodId, methodId);
        if (isDelete != null) {
            query.eq(MethodPhase::getIsDelete, isDelete.getValue());
        }
        query.orderByAsc(MethodPhase::getSort, MethodPhase::getIsDelete);
        return methodPhaseMapper.selectList(query);
    }

    @Override
    public boolean save(MethodPhase phase) {
        methodPhaseMapper.insert(phase);
        if (phase.getSourcePhaseId() == null) {
            MethodPhase upSource = new MethodPhase();
            upSource.setSourcePhaseId(phase.getId());
            upSource.setId(phase.getId());
            methodPhaseMapper.updateById(upSource);
        }
        return true;
    }

    @Override
    public MethodPhase selectById(Long methodPhaseId) {
        return methodPhaseMapper.selectById(methodPhaseId);
    }
}
